<template>
  <el-dialog 
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="tool-modal"
    destroy-on-close
    width="65%"
    top="12vh"
    @close="handleClose"
    style="margin-left: 12%;"
  >
  <div class="smart-selection-container">
    <div class="smart-selection-header">
        <el-button class="how-to-button">
          如何选择区域
        </el-button>
        <div class="header-controls">
          <el-button class="control-button back-button" @click="handleUndo">
            <el-icon><ArrowLeft /></el-icon> 撤回
          </el-button>
          <el-button class="control-button delete-button" @click="handleDelete">
          <el-icon><Delete /></el-icon> 删除
        </el-button>
          <el-button class="control-button confirm-button" @click="handleConfirm">
          确定
        </el-button>
      </div>
    </div>

    <div class="smart-selection-content">
      <div class="image-area" ref="imageAreaRef">
        <img 
          v-if="imageUrl" 
          :src="imageUrl" 
          alt="选区图片" 
          class="selection-image"
          ref="imageRef"
          @load="initializeCanvas" 
          crossorigin="anonymous"
        />
        <canvas 
          ref="selectionCanvasRef" 
          class="selection-canvas"
          @mousedown="startSelection"
          @mouseleave="endSelection"
            @contextmenu.prevent
        ></canvas>
          
          <!-- 模式提示 -->
          <div class="mode-indicator" v-if="!isDefaultMode">
            <div class="mode-text">
              {{ selectionMode === 'include' ? '选取模式' : '排除模式' }}
            </div>
        </div>
      </div>
    </div>

      <div class="smart-selection-footer-wrapper">
    <div class="smart-selection-footer">
          <el-button 
            class="selection-button select-button" 
            :class="{ active: !isDefaultMode && selectionMode === 'include' }" 
            @click="setSelectionMode('include')"
          >
        选取
      </el-button>
          <el-button 
            class="selection-button exclude-button" 
            :class="{ active: !isDefaultMode && selectionMode === 'exclude' }" 
            @click="setSelectionMode('exclude')"
          >
        排除
      </el-button>
    </div>
  </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, defineProps, defineEmits, nextTick, watch } from 'vue';
import { ArrowLeft, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash-es';

interface Props {
  imageUrl: string;
  visible: boolean;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'selection-complete', data: { mask: string; selectionType: 'include' | 'exclude' }): void;
  (e: 'close'): void;
}>();

// Refs
const imageAreaRef = ref<HTMLDivElement | null>(null);
const imageRef = ref<HTMLImageElement | null>(null);
const selectionCanvasRef = ref<HTMLCanvasElement | null>(null);
const selectionContext = ref<CanvasRenderingContext2D | null>(null);

// State
const points = ref<Array<{ x: number; y: number; type: 'include' | 'exclude' }>>([]);
const hasSelection = ref(false);
const selectionHistory = ref<Array<Array<{ x: number; y: number; type: 'include' | 'exclude' }>>>([]);
const isSelecting = ref(false);
const selectionType = ref<'include' | 'exclude'>('include');
// Determines if we're in the default mode (left=include, right=exclude) or in a specific mode
const isDefaultMode = ref<boolean>(true);
// Selection mode determines the current operation type when not in default mode
const selectionMode = ref<'include' | 'exclude'>('include');

// Methods
// Set the selection mode (include/exclude)
const setSelectionMode = (mode: 'include' | 'exclude') => {
  selectionMode.value = mode;
  // Update the selection type for the final output
  selectionType.value = mode;
  // Switch to specific mode (non-default)
  isDefaultMode.value = false;
};

const initializeCanvas = () => {
  const canvas = selectionCanvasRef.value;
  const image = imageRef.value;
  const container = imageAreaRef.value;
  
  if (!canvas || !image || !container) return;
  
  // Wait for the image to be fully rendered
  nextTick(() => {
    // Get the image's actual display size and position
    const imgRect = image.getBoundingClientRect();
    
    // Set canvas size to match the image display dimensions
    canvas.width = imgRect.width;
    canvas.height = imgRect.height;
    
    // Position canvas to overlap perfectly with the image
    canvas.style.position = 'absolute';
    canvas.style.top = `${imgRect.top - container.getBoundingClientRect().top}px`;
    canvas.style.left = `${imgRect.left - container.getBoundingClientRect().left}px`;
    canvas.style.pointerEvents = 'auto';
    canvas.style.zIndex = '10';
    
    // Get the canvas context
    const ctx = canvas.getContext('2d');
    if (ctx) {
      selectionContext.value = ctx;
      // Clear canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  });
};

const startSelection = (e: MouseEvent) => {
  if (!selectionContext.value || !selectionCanvasRef.value) return;
  
  const rect = selectionCanvasRef.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  
  // 确定当前选择类型
  let currentType: 'include' | 'exclude';
  if (isDefaultMode.value) {
    // 默认模式下，左键是选择，右键是排除
    currentType = e.button === 2 ? 'exclude' : 'include';
  } else {
    // 特定模式下，使用选定的模式
    currentType = selectionMode.value;
  }
  
  // 添加点击点到历史
  const newPoint = { x, y, type: currentType };
  points.value.push(newPoint);
  selectionHistory.value.push([newPoint]);
  
  // 绘制点
  const pointColor = currentType === 'include' ? '#00CCFF' : '#FF69B4';
  drawPoint(x, y, pointColor);
  
  hasSelection.value = true;
  
  // 每添加一个点后，可以触发掩码生成（这里可以使用防抖处理）
  debouncedRequestMask();
};

const endSelection = () => {
  // 点击模式下不需要特殊处理结束动作
};

const drawPoint = (x: number, y: number, color: string) => {
  const ctx = selectionContext.value;
  if (!ctx) return;
  
  ctx.beginPath();
  ctx.arc(x, y, 8, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
};

const processSelection = () => {
  // This would trigger AI processing based on the points
  const ctx = selectionContext.value;
  if (!ctx || points.value.length < 2) return;
  
  // Get the type from the first point
  const type = points.value[0].type;
  
  // Draw the selection outline
  ctx.beginPath();
  ctx.moveTo(points.value[0].x, points.value[0].y);
  
  for (let i = 1; i < points.value.length; i++) {
    ctx.lineTo(points.value[i].x, points.value[i].y);
  }
  
  ctx.closePath();
  // Set stroke color based on selection type
  ctx.strokeStyle = type === 'include' ? '#00CCFF' : '#FF69B4';
  ctx.lineWidth = 2;
  ctx.stroke();
  
  // Add some visual feedback
  ElMessage.success(type === 'include' ? '已创建选取区域' : '已创建排除区域');
};

const handleUndo = () => {
  if (selectionHistory.value.length > 0) {
    selectionHistory.value.pop();
    redrawSelections();
  } else {
    ElMessage.info('没有可撤回的操作');
  }
};

const handleDelete = () => {
  // Clear all selections
  selectionHistory.value = [];
  clearCanvas();
  hasSelection.value = false;
  ElMessage.info('已清除所有选区');
};

const clearCanvas = () => {
  const ctx = selectionContext.value;
  const canvas = selectionCanvasRef.value;
  if (!ctx || !canvas) return;
  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
};

const redrawSelections = () => {
  clearCanvas();
  
  // Redraw all selections from history
  selectionHistory.value.forEach((pointSet: Array<{ x: number; y: number; type: 'include' | 'exclude' }>) => {
    const ctx = selectionContext.value;
    if (!ctx || pointSet.length < 2) return;
    
    // Get the selection type from the first point
    const type = pointSet[0].type || 'include';
    const strokeColor = type === 'include' ? '#00CCFF' : '#FF69B4';
    
    ctx.beginPath();
    ctx.moveTo(pointSet[0].x, pointSet[0].y);
    
    for (let i = 1; i < pointSet.length; i++) {
      ctx.lineTo(pointSet[i].x, pointSet[i].y);
    }
    
    ctx.closePath();
    ctx.strokeStyle = strokeColor;
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // Draw points
    pointSet.forEach((point: { x: number; y: number; type: 'include' | 'exclude' }) => {
      const pointColor = point.type === 'include' ? '#00CCFF' : '#FF69B4';
      drawPoint(point.x, point.y, pointColor);
    });
  });
  
  hasSelection.value = selectionHistory.value.length > 0;
};

// Reset to default mode
const resetToDefaultMode = () => {
  isDefaultMode.value = true;
};

const handleSelect = () => {
  selectionType.value = 'include';
  finishSelection();
};

const handleExclude = () => {
  selectionType.value = 'exclude';
  finishSelection();
};

const finishSelection = () => {
  if (!hasSelection.value) {
    ElMessage.warning('请先创建选区');
    return;
  }
  
  // Generate mask from selections
  const mask = generateMaskFromSelections();
  
  // Emit selection complete event with mask data
  emit('selection-complete', { 
    mask, 
    selectionType: selectionType.value 
  });
  
  // Close the selection dialog
  emit('update:visible', false);
  emit('close');
};

const generateMaskFromSelections = (): string => {
  // In a real implementation, this would create a proper mask
  // For now, we return the canvas as a data URL
  const canvas = selectionCanvasRef.value;
  if (!canvas) return '';
  
  return canvas.toDataURL('image/png');
};

const handleConfirm = () => {
  if (!hasSelection.value) {
    ElMessage.warning('请先创建选区');
    return;
  }
  
  finishSelection();
};

const handleClose = () => {
  emit('update:visible', false);
  emit('close');
};

// Watch for visibility changes
watch(() => props.visible, (newIsVisible: boolean) => {
  if (newIsVisible) {
    // Reset to default mode when dialog is opened
    resetToDefaultMode();
    
    nextTick(() => {
      initializeCanvas();
    });
  }
});

// Initialize on mount
onMounted(() => {
  if (props.visible) {
    nextTick(() => {
      initializeCanvas();
    });
  }
  
  window.addEventListener('resize', initializeCanvas);
});

// Clean up on unmount
onUnmounted(() => {
  window.removeEventListener('resize', initializeCanvas);
});

// 添加防抖处理的掩码请求函数
const debouncedRequestMask = debounce(() => {
  if (points.value.length === 0) return;
  
  // 这里是模拟代码，实际使用时请替换为真实API调用
  console.log('请求生成掩码:', points.value);
  // 在实际应用中，这里应该调用后端API来生成掩码
  // processSelectionWithAPI(points.value);
}, 300);
</script>

<style scoped>
.smart-selection-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 0;
  overflow: hidden;
  max-height: 100vh;
}

.smart-selection-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #000;
  height: 60px;
}

.how-to-button {
  height: 40px;
  background-color: #000;
  border: 1px solid #000;
  color: white;
  border-radius: 5px;
  font-size: 15px;
  font-weight: 500;
  padding: 0 20px;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.control-button {
  font-size: 14px;
  height: 40px;
  font-weight: 500;
  border-radius: 5px;
}

.back-button, .delete-button {
  background-color: #000;
  color: #E6C989;
  border: 1px solid #444;
  padding: 0 15px;
}

.back-button:hover, .delete-button:hover {
  background-color: #222;
}

.confirm-button {
  background-color: #E6C989;
  border-color: #E6C989;
  color: #000;
  padding: 0 20px;
}

.confirm-button:hover,
.confirm-button:focus {
  background-color: #D6BD8F;
  border-color: #D6BD8F;
}

.smart-selection-content {
  flex: 1;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: #808080;
  height: 440px; /* Set fixed height */
}

.image-area {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.selection-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.selection-canvas {
  position: absolute;
  top: 0;
  left: 0;
  cursor: crosshair;
}

.smart-selection-guide {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  padding: 15px 20px;
  border-radius: 8px;
  text-align: center;
  pointer-events: none;
}

.guide-text {
  color: white;
  font-size: 16px;
}

.selection-instruction {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 30px;
  background: rgba(0, 0, 0, 0.7);
  padding: 12px 20px;
  border-radius: 8px;
}

.instruction-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.instruction-text {
  color: white;
  font-size: 14px;
}

.dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.dot.green {
  background-color: #00CCFF;
}

.dot.red {
  background-color: #FF4040;
}

.smart-selection-footer-wrapper {
  display: flex;
  justify-content: center;
  background: #fff;
  padding: 15px 0;
}

.smart-selection-footer {
  display: flex;
  gap: 15px;
  width: 60%; /* Reduced width */
  max-width: 500px;
}

.selection-button {
  flex: 1;
  height: 40px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 40px;
}

.selection-button.active {
  transform: scale(1.05);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
}

.select-button {
  background: #E6C989;
  color: #000;
  border: none;
}

.select-button:hover,
.select-button:focus,
.select-button.active {
  background: #D6BD8F;
  color: #000;
}

.exclude-button {
  background: #333;
  color: white;
  border: none;
}

.exclude-button:hover,
.exclude-button:focus,
.exclude-button.active {
  background: #222;
}

/* Add tool-modal specific styles to match other modals */
:deep(.tool-modal) {
  display: flex;
  justify-content: center;
}

:deep(.el-dialog) {
  border-radius: 0;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  display: none;
}

:deep(.el-dialog__body) {
  padding: 0;
}

/* 添加模式指示器样式 */
.mode-indicator {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  padding: 8px 16px;
  border-radius: 20px;
  z-index: 20;
}

.mode-text {
  color: white;
  font-size: 14px;
  font-weight: 500;
}
</style>
